/**
 * 选择TAB
 */
jQuery.chooseTab=function(obj){
	var $item = $(obj);
	if($item.parent().hasClass("current")) return;
	var $tab = $item.parents(".tab");
	if(!$tab||$tab.length==0) return;
	
	$item.parent().siblings().removeClass("current");
	$item.parent().addClass("current");
	
	var itemId=$item.attr("item_id");
	var container=$(">div.content",$tab);
	var itemContent=container.children("div[item_id="+itemId+"]");
	if(itemContent.length>0){
		container.children().hide();
		itemContent.show();
	}else{
		container.children().hide();
		container.append("<div item_id="+itemId+">"+obj.innerHTML+"</div>");
		//$("<div item_id="+itemId+">"+obj.innerHTML+"</div>").appendTo(container);
	}
}

/**
 * 根据参数名称获取参数值
 * eg:?p1=123&p2=456
 * 当name为p1时返回123，为p2时返回456
 * @param name 参数名称，不区分大小写
 * @return 返回参数名称对应的值
 * @author chenxiang
 */
jQuery.getParam=function(name,href) {
	href=href||location;
    var r = (href.search+href.hash).match(new RegExp("[\?\&\#]" + name + "=([^\&|\#]*)(\&|\#?)", "i"));
    return r?unescape(r[1]):null;
}

/**
 * 设为首页
 */
jQuery.setHome=function(url){
	url=url||location.href;
	try { 
		document.body.style.behavior = 'url(#default#homepage)'; 
		document.body.setHomePage(url); 
	} catch (e) { 
		if (window.netscape) { 
			try { 
				netscape.security.PrivilegeManager.enablePrivilege("UniversalXPConnect"); 
			} catch (e) { 
				alert("此操作被浏览器拒绝！\n请在浏览器地址栏输入“about:config”并回车\n然后将 [signed.applets.codebase_principal_support]的值设置为'true',双击即可。"); 
			} 
			var prefs = Components.classes['@mozilla.org/preferences-service;1'].getService(Components.interfaces.nsIPrefBranch); 
			prefs.setCharPref('browser.startup.homepage', url); 
		} 
	}
}

/**
 * 添加收藏
 */
jQuery.addFavorite=function(url,title){
	url=url||location.href;
	title=title||document.title;
	if(document.all) { 
		try{ 
			window.external.addFavorite(url, title); 
		}catch (e1){ 
			try{ 
				window.external.addToFavoritesBar(url, title); 
			}catch (e2){ 
				alert('加入收藏失败，请您手工加入。') 
			} 
		} 
	} else if (window.external) { 
		window.sidebar.addPanel(title, url,""); 
	} else { 
		alert('加入收藏失败，请您手工加入。') 
	} 
}
/**
 * 分页工具条
 * 使用示例：
 * 1 $.pageBar('pagebar',53,function(pageindex){})
 * 	参数说明：	
 * 		ID:'pagebar'
 * 		total:53
 * 		pagesize:20（这是默认值）
 * 		curpage:1（这是默认值）
 * 		action:function(pageindex)
 * 
 * 2.$.pageBar('pagebar',53,15,function(pageindex){})
 * 	参数说明：	
 * 		ID:'pagebar'
 * 		total:53
 * 		pagesize:15
 * 		curpage:1（这是默认值）
 * 		action:function(pageindex)
 * 
 * 3.$.pageBar('pagebar',53,15,2,function(pageindex){})
 * 	参数说明：	
 * 		ID:'pagebar'
 * 		total:53
 * 		pagesize:15
 * 		curpage:2
 * 		action:function(pageindex)
 * 
 * @param ID DIV标识ID或DIV对象
 * @param total	记录总数
 * @param pagesize	每页显示的记录数（默认为20条记录）
 * @param curpage 当前页（默认为第一页）
 * @param action	点击页码action（回调函数）
 * @author 陈祥
 */
jQuery.pageBar=function(ID,total,pagesize,curpage,action,simple){
	var render=typeof(ID)=="string"?$("#"+ID):$(ID);
	if(render.attr("loaded")=="true") return render;
	render.attr("loaded","true");
	var defPagesize=20,defCurpage=1;
	$.getScript("/js/ext/jquery.pagebar.js",function(){
		$.getCSS("/js/ext/jquery.pagebar.css",function(){
			simple=action===true||curpage===true||simple===true;
			
			if ( $.isFunction( pagesize ) ) {
				action = pagesize;
				pagesize = defPagesize;
				curpage = defCurpage;
			} else if ($.isFunction( curpage )){
				action = curpage;
				curpage = defCurpage;
			}
			
			var callback=function(pageIndex,event){
				event=event||window.event;
				event.cancelBubble = true; 
				try{
				e.stopPropagation();
				}catch(e){}
				$.fn.setCurrentPage(this,pageIndex);
				action(pageIndex)
				//这里进行ajax异步数据处理
				//通过提交表单，或着使用location.href
			}
			
			var render=typeof(ID)=="string"?$("#"+ID):$(ID);
			
			var setting={
				//pagebar 对象div
				renderTo: render,
                //总页码
				totalpage: Math.ceil(total/pagesize),
				//当前页码
				currentPage: curpage,
				//是否显示简单形式,简单形式：“首页、上一页、下一页、尾页”
				simple:simple,
				//点击页码action
				onClickPage : callback
			}
			
			$.fn.jpagebar(setting);
		})
	})
}

/**
 * 简单分页工具条，“首页、上一页、下一页、尾页”
 * 使用示例：
 * 1 $.pageBarEx('pagebar',53,function(pageindex){})
 * 	参数说明：	
 * 		ID:'pagebar'
 * 		total:53
 * 		pagesize:20（这是默认值）
 * 		curpage:1（这是默认值）
 * 		action:function(pageindex)
 * 
 * 2.$.pageBarEx('pagebar',53,15,function(pageindex){})
 * 	参数说明：	
 * 		ID:'pagebar'
 * 		total:53
 * 		pagesize:15
 * 		curpage:1（这是默认值）
 * 		action:function(pageindex)
 * 
 * 2.$.pageBarEx('pagebar',53,15,2,function(pageindex){})
 * 	参数说明：	
 * 		ID:'pagebar'
 * 		total:53
 * 		pagesize:15
 * 		curpage:2
 * 		action:function(pageindex)
 * 
 * @param ID DIV标识ID或DIV对象
 * @param total	记录总数
 * @param pagesize	每页显示的记录数（默认为20条记录）
 * @param curpage 当前页（默认为第一页）
 * @param action	点击页码action（回调函数）
 * @author 陈祥
 */
jQuery.pageBarEx=function(ID,total,pagesize,curpage,action){
	$.pageBar(ID,total,pagesize,curpage,action,true);
}

jQuery.toServiceUrl=function(url){
	if(url.match(/\/(.*)\.\w\??/)) return url;
	
	var root="/services";
	url=root+(url.indexOf("/")==0?url:"/"+url);
	return url+(url.indexOf("?")>0?"&":"?")+"_t="+(new Date().getTime());
}

/**
 * Create a cookie with the given name and value and other optional parameters.
 *
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Set the value of a cookie.
 * @example $.cookie('the_cookie', 'the_value', {expires: 7, path: '/', domain: 'jquery.com', secure: true});
 * @desc Create a cookie with all available options.
 * @example $.cookie('the_cookie', 'the_value');
 * @desc Create a session cookie.
 * @example $.cookie('the_cookie', null);
 * @desc Delete a cookie by passing null as value.
 *
 * @param String name The name of the cookie.
 * @param String value The value of the cookie.
 * @param Object options An object literal containing key/value pairs to provide optional cookie attributes.
 * @option Number|Date expires Either an integer specifying the expiration date from now on in days or a Date object.
 *                             If a negative value is specified (e.g. a date in the past), the cookie will be deleted.
 *                             If set to null or omitted, the cookie will be a session cookie and will not be retained
 *                             when the the browser exits.
 * @option String path The value of the path atribute of the cookie (default: path of page that created the cookie).
 * @option String domain The value of the domain attribute of the cookie (default: domain of page that created the cookie).
 * @option Boolean secure If true, the secure attribute of the cookie will be set and the cookie transmission will
 *                        require a secure protocol (like HTTPS).
 * @type undefined
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */

/**
 * Get the value of a cookie with the given name.
 *
 * @example $.cookie('the_cookie');
 * @desc Get the value of a cookie.
 *
 * @param String name The name of the cookie.
 * @return The value of the cookie.
 * @type String
 *
 * @name $.cookie
 * @cat Plugins/Cookie
 * @author Klaus Hartl/klaus.hartl@stilbuero.de
 */
jQuery.cookie = function(name, value, options) {
    if (typeof value != 'undefined') { // name and value given, set cookie
    	if(typeof options == "number") options={expires:options};
        options = options || {};
        if (value === null) {
            value = '';
            options.expires = -1;
        }
        var expires = '';
        if (options.expires && (typeof options.expires == 'number' || options.expires.toUTCString)) {
            var date;
            if (typeof options.expires == 'number') {
                date = new Date();
                date.setTime(date.getTime() + (options.expires * 24 * 60 * 60 * 1000));
            } else {
                date = options.expires;
            }
            expires = '; expires=' + date.toUTCString(); // use expires attribute, max-age is not supported by IE
        }
        var path = options.path ? '; path=' + options.path : '';
        var domain = options.domain ? '; domain=' + options.domain : '';
        var secure = options.secure ? '; secure' : '';
        document.cookie = [name, '=', encodeURIComponent(value), expires, path, domain, secure].join('');
    } else { // only name given, get cookie
        var cookieValue = null;
        if (document.cookie && document.cookie != '') {
            var cookies = document.cookie.split(';');
            for (var i = 0; i < cookies.length; i++) {
                var cookie = jQuery.trim(cookies[i]);
                // Does this cookie string begin with the name we want?
                if (cookie.substring(0, name.length + 1) == (name + '=')) {
                    cookieValue = decodeURIComponent(cookie.substring(name.length + 1));
                    break;
                }
            }
        }
        return cookieValue;
    }
};
jQuery.get=function( url, data, callback, type, async ) {
		async=!(data===false||callback===false||type===false||async===false);
		
		if ( $.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = null;
		}
		return $.ajax({
			type: "GET",
			url: $.toServiceUrl(url),
			data: data,
			success: callback,
			dataType: type||"json",
			cache: false,
			async: async===false?false:true
		});
}
jQuery.post=function( url, data, callback, type, async ) {
		// shift arguments if data argument was omited
		if ( $.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = {};
		}
		
		if(typeof(type)=="boolean"){
			async=type;
			type="json";
		}

		return $.ajax({
			type: "POST",
			url: $.toServiceUrl(url),
			data: data,
			success: callback,
			dataType: type||"json",
			cache: false,
			async: async===false?false:true
		});
	},

jQuery.put=function(url, data, callback, type, async){
		if ( $.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = {};
		}
		
		if(typeof(type)=="boolean"){
			async=type;
			type="json";
		}

		return $.ajax({
			type: "PUT",
			url: $.toServiceUrl(url),
			data: data,
			success: callback,
			dataType: type||"json",
			cache: false,
			async: async===false?false:true
		});
	},
	
jQuery.del=function( url, data, callback, type, async){
		if ( $.isFunction( data ) ) {
			type = type || callback;
			callback = data;
			data = {};
		}
		
		if(typeof(type)=="boolean"){
			async=type;
			type="json";
		}

		return $.ajax({
			type: "DELETE",
			url: $.toServiceUrl(url),
			data: data,
			success: callback,
			dataType: type||"json",
			cache: false,
			async: async===false?false:true
		});
	}

jQuery.cntw=function(){
	if($.cookie("__ST__")!="traditionalized"){
		$("#cntw").css("cursor","pointer").click(function(){
			$.cookie("__ST__","traditionalized");
			$.cntw();
		})
		return;
	}
	$.getScript("/js/ext/jquery.cntw.js",function(){
		var isFirst = true;
		$("#cntw").css("cursor","pointer").unbind("click").click(function(){
			if(!isFirst)
				$.cookie("__ST__",$.cookie("__ST__")=="traditionalized"?null:"traditionalized",{expires:7});
			isFirst=false;
			$.translate(this);
		}).click();
	});
}
$(document).ready(function(){
	$.cntw();//简繁切换
});